//
//  ZYComposeViewController.swift
//  weiboZY
//
//  Created by 赵勇 on 16/5/19.
//  Copyright © 2016年 赵勇. All rights reserved.
//

import UIKit
import SVProgressHUD


class ZYComposeViewController: UIViewController, UITextViewDelegate {

    // 懒加载
    private lazy var rightButton:UIButton = {
       
        let btn = UIButton()
        btn.addTarget(self, action: "sendAction", forControlEvents: .TouchUpInside)
        btn.setTitle("发送", forState: .Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: .Disabled)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setBackgroundImage(UIImage(named:"common_button_orange"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), forState: .Highlighted)
        btn.setBackgroundImage(UIImage(named:"common_button_white_disable" ), forState: .Disabled)
        btn.frame.size = CGSize(width: 45, height: 30)
        return btn
        
    }()
    
    // 添加toolbar
    private lazy var toolBar: ZYComposeToolBar = {
        
       let bar = ZYComposeToolBar(frame: CGRectZero)
        return bar
        
    }()
    
    // 添加表情键盘
    private lazy var emoticonKeyBoard:ZYEmoticonKeyBoard = {
        
        let view = ZYEmoticonKeyBoard()
        view.size = CGSize(width: self.textView.width, height: 216)
        return view
        
    }()
    
    // 自定义titleView
    private lazy var titleView:UILabel = {
        
        let label = UILabel(textColor: UIColor.darkGrayColor(), font: 17)
        
        if let name = ZYUserAccountViewModel.sharedUserAccount.userAccount?.name {
            let title = "发微博\n\(name)"
            
            let range = (title as NSString).rangeOfString(name)
            
            let attributedStr = NSMutableAttributedString(string: title)
   
            attributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: range)
             attributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(15), range: range)
            label.attributedText = attributedStr
            
        } else {
          label.text = "发微博"
        }

        label.numberOfLines = 0
        label.textAlignment = .Center
        label.sizeToFit()
        
        return label
        
    }()
    
    // 自定义textView
    private lazy var textView: ZYComposeTextView = {
        let view = ZYComposeTextView()
        // 设置代理
        view.delegate = self
        view.alwaysBounceVertical = true
        view.font = UIFont.systemFontOfSize(15)
        
        view.placeHolderStr = "老四 你想说啥！老四 你想说啥！老四 你想说啥！老四 你想说啥！老四 你想说啥！老四 你想说啥！老四 你想说啥！老四 你想说啥！"
        return view
        
    }()
    //  自定义配图
    private lazy var pictureView: ZYComposePictureView = {
        let view = ZYComposePictureView()
        view.backgroundColor = self.view.backgroundColor
        return view
    }()
    
    //  哈哈
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        // 监听键盘改变
         NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChageFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 监听点击按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSelectEmoticon:", name: didSelectEmoticonBtnNotification, object: nil)
        // 监听删除按钮的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "delectEmoticon", name: DidselectDelectEmoticanNotification, object: nil)

    }

    @objc private func delectEmoticon() {
    
     textView.deleteBackward()
        
    }
    
    
    private func setupUI() {
        setupNav()
        view.backgroundColor = UIColor.whiteColor()
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.addSubview(pictureView)
        
        // 设置约束
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.trailing.equalTo(view)
            make.leading.equalTo(view)
            make.bottom.equalTo(toolBar.snp_top)
        }
        toolBar.snp_makeConstraints { (make) -> Void in
    
            make.trailing.equalTo(view)
            make.leading.equalTo(view)
            make.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        
        pictureView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView).offset(100)
            make.centerX.equalTo(textView)
            make.width.equalTo(textView).offset(-20)
            make.height.equalTo(textView.snp_width).offset(-20)
        }
        
        
        toolBar.didSeletedButtonClosure = { [weak self](type: ZYComposeToolBarButtonType) in
            
            switch type {
                
            case.Picture:
                print("picture")
                // 选择图库
                self?.didSelectedPicture()
                
            case.Mention:
                print("mention")
            case.Trend:
                print("trent")
            case.Emoticon:
                print("emotion")
                self?.didSelectedEmoticon()
            case.Add:
                print("add")
                
            }
            
            
        }
        
        // 添加图片按钮的闭包
        pictureView.addImageClosure = {
            
            self.didSelectedPicture()
            
        }
        
        
    }
    
    deinit {
        
        
        NSNotificationCenter.defaultCenter().removeObserver(self)
        
    }
    
    // 设置导航栏视图
    private func setupNav() {
        
       navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 15, target: self, action: "cancleAction")
       navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        // 设置右侧按钮不可用
       navigationItem.rightBarButtonItem?.enabled = false
        // 添加titleView
       navigationItem.titleView = titleView
        
    }
    
    
    // 设置点击事件
    @objc private func cancleAction() {
        
        self.view.endEditing(true)
        
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    // 键盘监听事件
    @objc private func keyboardChageFrame(noti: NSNotification) {
        
        let keyboardFrame = (noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]! as! NSValue).CGRectValue()
        
        let animationDuration = (noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]! as! NSNumber).doubleValue
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - view.frame.size.height)
            
        }
        
        UIView.animateWithDuration(animationDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        
    }
    
    // 表情按钮监听键
    @objc private func didSelectEmoticon(noti: NSNotification) {

        guard let emotion = noti.object as? ZYEmoticon else{
            return
        }
        
        print(emotion.type)
        
        textView.insertEmoticon(emotion, font: textView.font!)
//        if emotion.type == "0" {
//
//            // 记录上一次的富文本
//            var originalAttar = NSMutableAttributedString(attributedString: textView.attributedText)
//            
//            // 1创建一个UIimage
//            let image = UIImage(named: emotion.path!)
//            
//            // 2 根据UIImage对象创建一个NSTextAttachment
//            let attachment = NSTextAttachment()
//            
//            attachment.image = image
//            
//            // 字体的高度
//            let fontHeight = textView.font!.lineHeight
//            attachment.bounds = CGRect(x: 0, y: -3, width: fontHeight, height: fontHeight)
//            
//            // 3 根据NSTextAttachment创建一个NSAttributedString
//            let attr = NSAttributedString(attachment: attachment)
//            
//            // 获取textview的选中范围
//            var range = textView.selectedRange
//            // 替换选中的字符串
//            originalAttar.replaceCharactersInRange(range, withAttributedString: attr)
//            
//            // 追加富文本
////            originalAttar.appendAttributedString(attr)
//            
//            // 设置富文本字体大小
//            originalAttar.addAttribute(NSFontAttributeName, value: textView.font!, range: NSMakeRange(0,originalAttar.length))
//            
//            // 设置富文本
//            textView.attributedText = originalAttar
//            // 每次点击按钮位置加 1
//            range.location += 1
//            // 设置选中范围为0
//            range.length = 0
//            // 选中范围
//            textView.selectedRange = range
//            
//        } else {
//            
//            textView.insertText((emotion.type! as NSString).emoji())
//
//        }
    }
    
    
    // 发送点击事件
    @objc private func sendAction() {
        
        
        
        
//        // 获取表情对应的文本附件
//        
//        var result = ""
//        
//        textView.attributedText.enumerateAttributesInRange(NSMakeRange(0, textView.attributedText.length), options: []) { (infoDic, range, _) -> Void in
//            
//            if let attachment = infoDic["NSAttachment"] as? ZYEmoticonTextAttachment {
//                // 信息文本附件 表qing
//                
//                let chs = attachment.emoticon?.chs
//                result += chs!
//                
//            } else {
//                // 信息是文本
//               let textStr = self.textView.attributedText.attributedSubstringFromRange(range).string
//                result += textStr
//                
//            }
//            
//        }
        
        
        // 发送带图片微博
        if pictureView.images.count > 0 {

            // 发送带文字文博
            let accesstoken = ZYUserAccountViewModel.sharedUserAccount.accessToken!
            
            let status = textView.emoticonText
            
            let img = pictureView.images.first!

            ZYNetWorkTools.sharedTool.upload(accesstoken, status: status, image: img, callBack: { (response, error) -> () in
                
                SVProgressHUD.show()
                
                if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("网络异常")
        
                    return
                    
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
            })
            
            
        } else {
            
            // 发送带文字文博
            let accesstoken = ZYUserAccountViewModel.sharedUserAccount.accessToken!
            let status = textView.emoticonText
            
            ZYNetWorkTools.sharedTool.sendUpdate(accesstoken, status: status) { (response, error) -> () in
                
                if error != nil {
                    
                    SVProgressHUD.showErrorWithStatus("网络异常")
                    return
                    
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
            }
        }
        

    }
    
    
    // MARK: UITextViewDelegate
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }


    
    
}



extension ZYComposeViewController:UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
       // 表情
    func didSelectedEmoticon(){
        
        if textView.inputView == nil {
            textView.inputView = emoticonKeyBoard
            
        } else {
            textView.inputView = nil
        }
        //  获取第一响应者
        textView.becomeFirstResponder()
        //  重写加载自定义的intputview
        textView.reloadInputViews()
        
        
    }
    
    
    
    
    func didSelectedPicture() {
        
        let pictureVc = UIImagePickerController()
        
        pictureVc.delegate = self
        
        //  是否支持这种类型
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            pictureVc.sourceType = .Camera
            
        } else {
            
            pictureVc.sourceType = .PhotoLibrary
        }
        
        // 判断前置摄像头是否可用
        if UIImagePickerController.isCameraDeviceAvailable(.Front) {
            print("前置摄像头可用")
        } else if UIImagePickerController.isCameraDeviceAvailable(.Rear) {
            print("后置摄像头可用")
        } else {
            print("摄像头不可用")
        }

        presentViewController(pictureVc, animated: true, completion: nil)
        
        
    }
    
    // 实现代理方法
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleImageWithWidth(300)
        
//        let data = UIImagePNGRepresentation(scaleImage)
        
//        data?.writeToFile("/Users/ZhaoSir/Desktop/2.png", atomically: true)
        
        pictureView.addImage(scaleImage)
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
//    // 等比压缩图片的方法
//    func scaleImageWithWidth(image: UIImage, scaleWidth: CGFloat) -> UIImage {
//        
//        let scaleHeight = scaleWidth / image.size.width * image.size.height
//        
//        let size = CGSize(width: scaleWidth, height: scaleHeight)
//        
//        // 开启图形上下文
//        UIGraphicsBeginImageContext(size)
//        
//        image.drawInRect(CGRect(origin: CGPointZero, size: size))
//        
//        // 获得压缩后的图片
//        let scaleImage = UIGraphicsGetImageFromCurrentImageContext()
//        
//        // 关闭图形上下文
//        UIGraphicsEndImageContext()
//        
//        return scaleImage
//    }
    
    
}






